/*
* webscoket
* 包含 链接，暂停，终止，信息处理等方法定义
* */
import vue from 'vue'
import constant from '@/constant'
import store from '@/store'
import vuxTool from '@/utils/open/vux-plugin'
import common from '@/utils/open/common'
import sys from '@/utils/open/sys'
let wsTimer = null
// eslint-disable-next-line
let closeTimer = null
// eslint-disable-next-line
let closeNum = 0
// eslint-disable-next-line
let connectNum = 3 // 超过三次，停止访问
export default {
  websocket() { // * 通知 'notice';   * 作业 'homework';   * 相册 'album';
    this.wsInitAck()
  },
  wsInitAck() {
    const _this = this
    // debugger
    if (!store.state.news.websocketInfo || store.state.news.websocketInfo.readyState === WebSocket.CLOSED) {
      this.wsConnect()
    }
    if (wsTimer) {
      clearTimeout(wsTimer)
      wsTimer = null
    }
    // if (connectNum>0) { // 超过三次，停止访问
    wsTimer = setTimeout(function() {
      _this.wsCheck()
      _this.wsInitAck()
    }, 10000)
    // }
    // connectNum--
  },
  wsCheck() {
    console.log('ws检测中......')
  },
  wsDisConnect(fn) { // 断开连接
    if (store.state.news.websocketInfo != null) {
      store.state.news.websocketInfo.close()
      store.state.news.websocketInfo = null
      if (fn) {
        fn()
      }
    }
  },
  wsConnect() { // 链接
    const token = store.state.user.token
    const wsUrl = constant.ws_ctx + 'ws/endpoint?token=' + token
    // console.log('wsUrl:', wsUrl)
    // 哦安短浏览器是否支持websocket
    if ('WebSocket' in window) {
      const url = 'ws://' + wsUrl
      store.state.news.websocketInfo = new WebSocket(url)
    } else {
      // 按需引入 sockjs.js
      // const head = document.head
      // const url = 'http://' + wsUrl
      // var oScript = document.createElement('script')
      // oScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.3.0/sockjs.js'
      // oScript.onload = function(e) {
      //   store.state.news.websocketInfo = new SockJS(url)
      // }
      // head.appendChild(oScript)
      // eslint-disable-next-line
      store.state.news.websocketInfo = new SockJS(url)
    }

    const _this = this
    // debugger
    store.state.news.websocketInfo.onopen = function(evnt) {
      console.log('连接服务器成功,准备上线')
      const onLine = { // 上线
        module: 'chat',
        type: 'onLine',
        data: {
          userId: store.state.user.userInfo.id, // 当前身份id
          unitId: store.state.user.curSelectRoleId // 当前身份id
        }
      }
      // debugger
      console.log('onLine:', onLine)
      _this.wsSend(onLine)
    }
    store.state.news.websocketInfo.onmessage = (res) => {
      console.log('收到消息-onmessage', res)
      _this.wsShowLog(JSON.parse(res.data))
    }
    store.state.news.websocketInfo.onerror = function(evnt) {
      console.log('报错信息', evnt)
    }
    store.state.news.websocketInfo.onclose = function(evnt) {
      console.log('websocket已断开服务!')
      if (closeTimer) {
        clearTimeout(closeTimer)
        closeTimer = null
      }
      closeTimer = setTimeout(function() { }, 250)
      // const p = new Promise(function(resolve, reject) {
      //   _this.wsDisConnect(() => {
      //     resolve()
      //   })
      // })
      // p.then(function() {
      //   closeNum++
      //   _this.wsConnect()
      // })
    }
  },
  wsChatConect(fn) {
    // const _this = this
    // debugger
    // store.state.news.websocketInfo.onopen = function(evnt) {
    //   console.log('连接服务器成功,准备上线')
    //   const onLine = { // 上线
    //     module: 'chat',
    //     type: 'onLine',
    //     data: {
    //       userId: store.state.user.userInfo.id, // 当前身份id
    //       unitId: store.state.user.curSelectRoleId // 当前身份id
    //     }
    //   }
    //   _this.wsSend(onLine)
    // }
    // store.state.news.websocketInfo.onmessage = (res) => {
    //   console.log(JSON.parse(res.data), '返回的结果')
    //   _this.wsShowLog(JSON.parse(res.data))
    // }
    // store.state.news.websocketInfo.onerror = function(evnt) {
    //   console.log(evnt, '报错信息')
    // }
    // store.state.news.websocketInfo.onclose = function(evnt) {
    //   console.log('websocket已断开服务!')
    //   if (closeTimer) {
    //     clearTimeout(closeTimer)
    //     closeTimer = null
    //   }
    //   closeTimer = setTimeout(function() {}, 250)
    //   const p = new Promise(function(resolve, reject) {
    //     _this.wsDisConnect(() => {
    //       resolve()
    //     })
    //   })
    // p.then(function() {
    //   closeNum++
    //   _this.wsConnect(that)
    // })
    // }
  },
  wsShowLog(res) {
    // console.log('收到消息 onmessage', res)
    // debugger
    // 消息数量处理 level、notice、homework、album、chat
    if (res.module === 'chat') { // 聊天
      this.wsMessageChat(res) // 处理聊天信息
    } else {
      const unread = store.state.user.unreadList
      console.log(unread, '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    }
  },
  wsCheckConnect(fn) { // 检测链接状态
    if (store.state.news.websocketInfo.readyState === 3) { //  连接已经关闭或者根本没有建立
      const _this = this
      const p = new Promise((resolve, reject) => {
        _this.wsConnect((res) => {
          if (res) { // 成功
            resolve()
          } else { // 失败
            reject()
          }
        })
      })
      p.then(() => {
        if (fn) {
          fn()
        }
      })
    } else {
      if (fn) {
        fn()
      }
    }
  },
  wsSend(params) {
    // console.log(store.state.news.websocketInfo)
    if (store.state.news.websocketInfo) {
      // debugger
      this.wsCheckConnect(() => {
        params = params || {}
        if (!params.unitId) {
          params.data.unitId = store.state.user.curSelectUnitId
        }
        // console.log('发送信息：', params)
        params = JSON.stringify(params)
        setTimeout(function() {
          // debugger
          store.state.news.websocketInfo.send(params)
        }, 250)
      })
    } else {
      console.error('未与服务器链接.')
      this.wsInitAck()
    }
  },
  wsMessageChat(res) {
    const data = res.data
    const chatPageStatus = window.sessionStorage.getItem('chatPageStatus')
    if (chatPageStatus === 'chatWindow') { // 聊天窗口打开中（直接显示）
      if (res.type === 'startChatRes') { // 进入聊天室后返回的结果

      } else if (res.type === 'startChatUserErr') { // 进入聊天室错误，发起用户不存在
        vuxTool.toast('发起用户不存在')
        vue.$router.go(-1)
        return
      } else if (res.type === 'startChatOtheruserErr') { // 进入聊天室错误，接收方用户不存在
        vuxTool.toast('接收方用户不存在')
        vue.$router.go(-1)
        return
      }

      // debugger
      const urlParams = common.getCurPathParam(1)
      // debugger
      const userInfo = store.state.user.userInfo
      if (userInfo.id === data.userId) { // 1.自己发的信息 userId:用户身份id
        // debugger
        // console.log('自己发的信息')
        const disName = data.userId + '-' + data.identityTime // 通过时间戳来确认当前信息发送状态
        if (!constant.chatRecordStore[disName]) {
          constant.chatRecordStore[disName] = {}
        }
        constant.chatRecordStore[disName] = data
        let sendNum = store.state.news.chatInfoNum
        sendNum++
        // that.$store.commit('updateChatInfoNum', sendNum)
        store.dispatch('news/updateChatInfoNum', sendNum)
      } else if (urlParams.otherUserId === data.userId) { // 2.对方发送的信息
        const disName = data.userId // 对方发送的信息，当前处于聊天窗口，只需要对方id即可
        // debugger
        if (!constant.chatRecordReceive[disName]) {
          constant.chatRecordReceive[disName] = []
        }
        constant.chatRecordReceive[disName].push(data)

        let receiveNum = store.state.news.chatInfoReceive
        receiveNum++
        // that.$store.commit('updateChatInfoReceive', receiveNum)
        store.dispatch('news/updateChatInfoReceive', receiveNum)
        // console.log(store.state.news)
      } else { // 3.第三方发送的信息 - 这里暂时没用上
        // debugger
        // console.log('接受别人的信息')
        // let disName = data.userId+'-'+data.otherUserId
        // if(!constant.chatRecordReceive[disName]){
        //   constant.chatRecordReceive[disName] = []
        // }
        // constant.chatRecordReceive[disName].push(data)
      }
    } else {
      // debugger
      // console.log('信息数量处理：聊天-chat')
      constant.infoTotal[res.module]++
      sys.caculatMailNum() // 计算消息未读消息 总数

      if (chatPageStatus === 'mailNews') { // 消息列表 mail-news.vue
        // console.log('当前是在消息列表',data)
        const disName = data.userId + '-' + data.otherUserId
        if (!constant.mailNewsRecord[disName]) {
          constant.mailNewsRecord[disName] = []
        }
        constant.mailNewsRecord[disName].push(data)
        let receiveNum = store.state.news.chatInfoReceive
        receiveNum++
        store.dispatch('news/updateChatInfoReceive', receiveNum)
      } else if (chatPageStatus === 'mailLink') { // mailLink: 通信录 mail-link.vues
        // console.log('当前是在通信录',data)
        const disName = data.userId + '-' + data.otherUserId
        if (!constant.chatRecordReceive[disName]) {
          constant.chatRecordReceive[disName] = []
        }
        constant.chatRecordReceive[disName].push(data)
        let receiveNum = store.state.news.chatInfoReceive
        receiveNum++
        store.dispatch('news/updateChatInfoReceive', receiveNum)
      } else { // 已退出聊天窗口（信息保存处理）
        const disName = data.userId + '-' + data.otherUserId
        if (!constant.chatRecordReceive[disName]) {
          constant.chatRecordReceive[disName] = []
        }
        constant.chatRecordReceive[disName].push(data)
        // console.log('已退出聊天窗口（信息保存处理）',constant.chatRecordReceive)
      }
    }
  }
}
